/**
 *  Copyright 2016年12月12日 北京福富软件技术股份有限公司
 *  All Rights Reserved.
 *  文件名称: EmailController  
 *  初始作者：g.huangshg
 *  初始版本：V1.0.0   
 *  完成日期： 2016年12月12日 
 */
package sys.controller;

import com.alibaba.fastjson.JSON;
import com.init.ConfigInitial;
import com.init.SingletonCache;
import com.util.LogUtil;
import com.util.PagedRequest;
import com.util.PagedResult;
import config.model.MailConfig;
import config.model.SmsConfig;
import config.service.ConfigService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import send.email.SendQQmail;
import sys.model.Msg;
import sys.model.Questionnaire;
import sys.model.User;
import sys.model.UserEmail;
import sys.service.EmailService;
import sys.service.QuestionnaireService;
import sys.util.UserUtil;

import javax.activation.MailcapCommandMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/********************************************************
 * 类名：EmailController
 * 功能：
 * 作者：g.huangshg 2016年12月12日
 * 修改记录：
 *      日期              修改人              修改说明
 ********************************************************/
@Controller
@RequestMapping("/Email")
public class EmailController {
    @Autowired
    EmailService emailService;
    @Autowired
    ConfigService configService;
    @Autowired
    private QuestionnaireService questionnaireService;
    @RequestMapping(value = "/update", method = { RequestMethod.POST,
            RequestMethod.GET })
    @ResponseBody
    public String update(HttpServletRequest request, HttpServletResponse response) throws Exception {

        JSONObject json = new JSONObject();
        return json.toString();
    }
    @RequestMapping(value = "/emailPage", method = { RequestMethod.POST, RequestMethod.GET })
    public String emailPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "jsp/sys/email/email";
    }


    @RequestMapping(value = "/getEmailBox", method = { RequestMethod.POST,
            RequestMethod.GET },produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String getEmailBox(HttpServletRequest request,PagedRequest pagedRequest,String type,String userid,String title,String readstatus){
      //  System.out.println(userid);
                boolean flag=false;
        if(type!=null) {
            if (type.equals("1")) {
                LogUtil.info("=====>发件箱");
                flag = true;
            } else if (type.equals("2")) {
                LogUtil.info("=====>收件箱");
                flag = true;
            } else if (type.equals("3")) {
                LogUtil.info("=====>垃圾箱");
                flag = true;

            }
        }
        LogUtil.info("分页参数:"+	pagedRequest.getPage());
        LogUtil.info("分页页数:"+	pagedRequest.getRows());
        LogUtil.info("排序序名:"+	pagedRequest.getSidx());
        LogUtil.info("排序方式:"+	pagedRequest.getSord());
        Integer id=0;
        if(userid!=null&&!userid.equals("")){
            try {
                id = Integer.parseInt(userid);
            }
            catch (Exception e)
            {
                id=0;
            }
        }
        else {
            User user = UserUtil.getUser(request);
            if(user!=null){
                id=user.getId();
            }
        }
        if(flag&&id!=null&&id!=0) {
            Map map = new HashMap();
            map.put("type", type);
            map.put("userid",id);
            map.put("title", title);
            map.put("readstatus", readstatus);
            map.put("page", pagedRequest.getPage());
            map.put("rows", pagedRequest.getRows());
            map.put("sidx", pagedRequest.getSidx());
            map.put("sord", pagedRequest.getSord());
            PagedResult<UserEmail> userList = emailService.getEmailBox(map);
           // System.out.println(JSON.toJSONString(userList));
            return JSON.toJSONString(userList);
        }
        else{
            return "{data:false}";
        }


    }



/*
* 发送邮件
*
* */
    @RequestMapping(value = "/sendMsg", method = { RequestMethod.POST, RequestMethod.GET },produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String sendMsg(HttpServletRequest request, HttpServletResponse response,String receverid,String title,String content) throws Exception {
        LogUtil.info("发送邮件===>");
        JSONObject json = new JSONObject();
        UserEmail userEmail=new UserEmail();
        Msg msg=new Msg();
        User user=UserUtil.getUser(request);
        if(user==null||user.getId()==null){
            json.put("status","error");
            json.put("oprate","发送失败");
            json.put("msg","请登入账号");
            LogUtil.info("===>发送失败");
        }
        else {
            User user2=new User();
            user2.setId(user.getId());
            user2.setUsername(user.getUsername());
            user2.setRealname(user.getRealname());
            user2.setUrl(user.getUrl());
            user2.setUsertype(user.getUsertype());
            userEmail.setSenduser(user2);
            userEmail.setReceverid(Integer.parseInt(receverid));
            userEmail.setSenderid(user.getId());
            userEmail.setMsgid(1);
            userEmail.setRecevestatus(true);
            userEmail.setSendstatus(true);
            userEmail.setReadstatus(true);
            msg.setCtime(new Date());
            msg.setTitle(title);
            msg.setContent(content);
            userEmail.setMsg(msg);
            int i = emailService.insert(userEmail);
           if(i<0){
               json.put("status","error");
               json.put("msg","发送失败");
               LogUtil.info("===>发送失败");
           }
           else{
               json.put("status","success");
               json.put("msg","发送成功");
               LogUtil.info("===>发送成功");
           }
        }
        return json.toString();
    }

    @RequestMapping(value = "/deleteMail", method = { RequestMethod.POST, RequestMethod.GET },produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String deleteMail(HttpServletRequest request, String type,String [] id) throws Exception {
        JSONObject json = new JSONObject();
        LogUtil.info("邮件状态改变====>");
      //  System.out.println(id.length+"  "+type);
       Map map =new HashMap();
        if(id!=null&&id.length>0&&type!=null&&!type.equals("")) {
            map.put("id", id);
            map.put("type", type);
           // map.put("title", title);

            int i = emailService.delete(map);
            if (i > 0) {
                json.put("status", true);
                json.put("msg", "删除成功");
            } else {
                json.put("status", false);
                json.put("msg", "删除失败!");
            }
        }
        else{
            json.put("status", false);
            json.put("msg", "非法url,参数错误!");
        }
        return json.toString();
    }

    @RequestMapping(value = "/updateStatus", method = { RequestMethod.POST, RequestMethod.GET })
    public String updateStatus(HttpServletRequest request, HttpServletResponse response,String recever,String title,String context) throws Exception {
        JSONObject json = new JSONObject();
        UserEmail userEmail=new UserEmail();
        userEmail.setId(7);
        userEmail.setRecevestatus(false);
        int i=emailService.update(userEmail);
        System.out.println(i);
        return json.toString();
    }

    /*
    *
    *   问卷推送  向   用户 发送邮件
    *
    * */
    @RequestMapping(value = "/sendQmail", method = { RequestMethod.POST, RequestMethod.GET },produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String sendQmail(HttpServletRequest request,int id) throws Exception {
        JSONObject json = new JSONObject();
        Date date =(Date)SingletonCache.getCacheElement("emailtime", SingletonCache.getCache(ConfigInitial.Init));
        boolean flag=true;
        if(date!=null){
            Calendar nowDate=Calendar.getInstance(),oldDate=Calendar.getInstance();
            nowDate.setTime(new Date());
            oldDate.setTime(date);
            long timeNow=nowDate.getTimeInMillis();
            long timeOld=oldDate.getTimeInMillis();
            long h=(timeNow-timeOld)/(1000*60*60);
            if(h<0){
                flag=false;
            }
        }
        if(flag){
            try {
                //  获取邮件信息
                Questionnaire q = questionnaireService.selectByPrimaryKey(id);
                Map map=new HashMap();
                map.put("page",1);
                map.put("rows",1);
                //  获取邮箱  配置
                PagedResult<MailConfig> rlist = configService.selectMail(map);
                MailConfig mc = rlist.getDataList().get(0);
                LogUtil.info("向全平台校友发送问卷推送邮件====>");
                StringBuffer url = request.getRequestURL();
                String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
                String questionUrl = tempContextUrl + "/Question/getQuestionnaire?id=" + q.getId();
                questionUrl = "打开问卷(" + q.getTitle() + ")链接:  " + questionUrl;
                List<String> list = new ArrayList<>();
                list.add("407050835@qq.com");
                SendQQmail.send(mc, questionUrl, list);
                json.put("status", "success");
                json.put("operate", "发送成功");
                json.put("msg", "校友将陆续收到推送信息");
                SingletonCache.addToCache("emailtime", new Date(), SingletonCache.getCache(ConfigInitial.Init));
            }catch (Exception e){
                json.put("status","error");
                json.put("operate","发送失败!");
                json.put("msg","邮箱配置错误!");
            }
            }
        else {
            LogUtil.info("一小时内已经发送过一次====>");
            json.put("status","error");
            json.put("operate","发送失败!");
            json.put("msg","一小时内已经发送过一次，请过后再试!");
        }


        return json.toString();
    }



}
